package com.banzhi.shop.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

/**
 * Created by Administrator on 2017/6/12.
 */

public class LoadMoreRecyclerView extends RecyclerView {

    //加载更多回调
    private LoadingMoreListener mLoadingMoreListener;

    //是否正在加载    结束后需要设置为false
    private boolean isLoadingMore;

    //当前可见最后一项
    private int lastVisibleItemPosition;

    public LoadMoreRecyclerView(Context context) {
        super(context);
        initListener();
    }

    public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initListener();
    }

    public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initListener();
    }


    public void initListener() {
        super.addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LayoutManager layoutManager = getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager) {
                    lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                } else if (layoutManager instanceof GridLayoutManager) {
                    lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
                }
                if (mLoadingMoreListener != null && !isLoadingMore && dy > 0) {
                    if (lastVisibleItemPosition + 1 == getAdapter().getItemCount()) {
                        setLoadingMore(true);
                        mLoadingMoreListener.LoadMore();
                    }
                }
            }
        });
    }




    public interface LoadingMoreListener {
        void LoadMore();
    }

    public LoadingMoreListener getLoadingMoreListener() {
        return mLoadingMoreListener;
    }

    public void setLoadingMoreListener(LoadingMoreListener mLoadingMoreListener) {
        this.mLoadingMoreListener = mLoadingMoreListener;
    }

    public boolean isLoadingMore() {
        return isLoadingMore;
    }

    public void setLoadingMore(boolean loadingMore) {
        isLoadingMore = loadingMore;
    }
}
